﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.Enums;
using mozhi.smarterp.AuthorCenter.Roles.Repositories;
using mozhi.smarterp.AuthorCenter.Users.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Identity;
using Volo.Abp.Identity.EntityFrameworkCore;

namespace mozhi.smarterp.AuthorCenter.Roles
{
    [ExposeServices(typeof(ICustomIdentityRoleRepository), IncludeDefaults = true)]
    public class CustomerIdentityRoleRepository : EfCoreIdentityRoleRepository, ICustomIdentityRoleRepository
    {
        public CustomerIdentityRoleRepository(IDbContextProvider<IIdentityDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string filter = null, List<RoleType> types = null, CancellationToken cancellationToken = default)
        {
            return await ((IQueryable<IdentityRole>)(await GetDbSetAsync().ConfigureAwait(continueOnCapturedContext: false)))
                .WhereIf(types != null, x => types.Contains(EF.Property<RoleType>(x, "RoleType")))
                .WhereIf(!filter.IsNullOrWhiteSpace(), (Expression<Func<IdentityRole, bool>>)((IdentityRole x) => x.Name.Contains(filter) || x.NormalizedName.Contains(filter)))
                .LongCountAsync(GetCancellationToken(cancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
        }

        public async Task<List<IdentityRole>> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, string filter = null, bool includeDetails = false, List<RoleType> types = null, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync().ConfigureAwait(continueOnCapturedContext: false)).IncludeDetails(includeDetails)
             .WhereIf(!filter.IsNullOrWhiteSpace(), (IdentityRole x) => x.Name.Contains(filter) || x.NormalizedName.Contains(filter))
             .WhereIf(types != null, x => types.Contains(EF.Property<RoleType>(x, "RoleType")))
             .OrderBy<IdentityRole>(sorting.IsNullOrWhiteSpace() ? "Name" : sorting)
             .PageBy(skipCount, maxResultCount)
             .ToListAsync(GetCancellationToken(cancellationToken))
             .ConfigureAwait(continueOnCapturedContext: false);
        }
    }
}
